package com.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthFilter implements Filter {

    @Override
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        boolean authenticated = false;
        String authorization = request.getHeader("authorization");
        System.out.println("authorization:" + authorization);
        if (authorization != null) {
            if (authorization.startsWith("Basic")) {
                authorization = authorization.substring(authorization.indexOf(' ') + 1);
                byte[] bytes = decoder.decodeBuffer(authorization);
                authorization = new String(bytes);
                String userName = authorization.substring(0, authorization.indexOf(':'));
                String password = authorization.substring(authorization.indexOf(':') + 1);
                System.out.println("userName:" + userName);
                System.out.println("password:" + password);
                authenticated = userName.equals("abc") && password.equals("abc");
            } else if (authorization.startsWith("Digest")) {
                String userName = authorization.substring(authorization.indexOf("username="));
                userName = userName.substring("username=\"".length());
                userName = userName.substring(0, userName.indexOf('"'));
                String password = authorization.substring(authorization.indexOf("response="));
                password = password.substring("response=\"".length());
                password = password.substring(0, password.indexOf('"'));
                authenticated = userName.equals("abc") && password.equals("3cf1135d3b8e20ddArray272d0628856Arraya56");
            }
        }
        if (!authenticated) {
            response.addHeader("WWW-Authenticate", "Basic realm=\"Tomcat Manager Application\"");
            response.sendError(401, "Unauthorized");
        } else {
            chain.doFilter(request, response);
        }

    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

}
